package com.stock.stockana.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;

import com.stock.publiclib.BaseActivity;
import com.stock.stockana.R;
import com.stock.stockana.constants.NetWorkConstants;
import com.stock.stockana.events.network.GetVersionCodeEvent;
import com.stock.stockana.ui.fragments.VersionNoticeFragment;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;

/**
 * ---------------------------------------------------
 * Description:
 * Author: ljgsonx
 * Belong to: com.stock.stockana.ui.activities
 * Time: 2016/3/17 10:12
 * ---------------------------------------------------
 */
public class VersionNoticeActivity extends BaseActivity {

    private static final String TAG = "VersionNoticeActivity->";

    private VersionNoticeFragment versionNoticeFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        versionNoticeFragment = new VersionNoticeFragment();
        addFragment(versionNoticeFragment);
        setToolbarPosTitle("版本信息");
        removeToolbarMenu();
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        EventBus.getDefault().register(this);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            getSupportFragmentManager().popBackStackImmediate();
        } else {
            finish();
            overridePendingTransition(R.anim.in_from_left, R.anim.out_from_right);
            if (MainActivity.instance == null) {
                startActivity(new Intent(this, MainActivity.class));
            }
        }
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

    @Subscribe
    public void onEventMainThread(GetVersionCodeEvent event) {
        stopProgress();
        if (event.getResponseCode() == NetWorkConstants.RESPONSE_CODE_OK) {
            //最新版本
            String versionInPoints_new = event.getResponseString();
            String[] versionNums_new = versionInPoints_new.split("\\.");
            String versionStr_new = "";
            for (int i = 0; i < versionNums_new.length; i++) {
                versionStr_new += versionNums_new[i];
            }
            int version_new = Integer.parseInt(versionStr_new);
            //旧版本
            String versionInPoints_old = getVersionName();
            String[] versionNums_old = versionInPoints_old.split("\\.");
            String versionStr_old = "";
            for (int i = 0; i < versionNums_old.length; i++) {
                versionStr_old += versionNums_old[i];
            }
            int version_old = Integer.parseInt(versionStr_old);
            //开始比较处理
            int num = versionNums_new.length - versionNums_old.length;
            if(num > 0) {
                version_old = version_old * (int)Math.pow(10 , num);
            }else if (num < 0) {
                version_new = version_new * (int)Math.pow(10 , num);
            }
            if (version_new > version_old) {
                Toast.makeText(this, "即将下载最新版本!", Toast.LENGTH_LONG).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        intent.setData(Uri.parse(NetWorkConstants.DOWNLOAD_APP));
                        startActivity(intent);
                    }
                }, 800);
            } else {
                Toast.makeText(this, "当前已是最新版本!", Toast.LENGTH_LONG).show();
            }
        }else {
            Toast.makeText(this, "网络错误,请稍后重试!", Toast.LENGTH_LONG).show();
        }
    }

    public String getVersionName(){
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        try {
            return packageManager.getPackageInfo(getPackageName(),0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "getVersionName error");
            e.printStackTrace();
        }
        return "";
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
